﻿using System;
using System.Linq;
using System.Windows.Forms;

using DevExpress.XtraTreeList.Nodes;
using BranchOfSansar.Sansar.Enquiry;
using System.IO;
using BranchOfSansar.Register.Trans;
using DevExpress.XtraEditors;

namespace BranchOfSansar.Register.Main
{
    public partial class frmContractList : Form
    {
        private bool IsBrowse;
        private bool tlstLoaded;
        public vw_Contracts Contract { get; set; }
        public frmContractList()
        {
            IsBrowse = false;
            InitializeComponent();
        }

        public frmContractList(bool is_browse)
            : this()
        {
            this.IsBrowse = is_browse;
        }

        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            frmContract frm = new frmContract();
            frm.Tag = "new";
            if (frm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                loadGrid();
            }
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            loadGrid();
        }

        private void loadGrid()
        {
            string Dist = string.Empty;
            string Quart = string.Empty;
            if (treeList1.Selection[0].ParentNode == null)
            {
                Dist = treeList1.Selection[0].Tag.ToString();
            }
            else
            {
                Quart = treeList1.Selection[0].Tag.ToString();
            }

            using (EnquiryClient obj = new EnquiryClient(Globals.Token))
            {
                gridApartment.DataSource = obj.ContractList(Dist, Quart, Convert.ToInt32(cmbBank.EditValue), Convert.ToInt32(cmbKass.EditValue)
                    , txtADugaar.Text, txtAName.Text, txtAKod.Text, Convert.ToInt32(cmbASection.EditValue), cmbCType.SelectedIndex > 0 ? cmbCType.SelectedIndex.ToString() : ""
                    , txtCName.Text, txtCReg.Text, txtCCode.Text, ((ComboItem)cmbCollector.SelectedItem).StrValue, txtContNo.Text
                    , txtToot.Text, txtProd1.Text, checkEdit1.Checked, dt1.DateTime, dt2.DateTime, txtUser.Text,txtPhone.Text,txtMail.Text,txtBill.Text);
            }
        }

        private void loadData()
        {
            dt1.DateTime = DateTime.Now.AddDays(-30);
            dt2.DateTime = DateTime.Now;
            using (EnquiryClient obj = new EnquiryClient(Globals.Token))
            {
                #region set Treelist data
                var Dist = obj.DistrictAndQuarterList();

                treeList1.BeginUpdate();
                treeList1.Columns.Add();
                treeList1.Columns[0].Caption = "Дүүрэг, хороо";
                treeList1.Columns[0].VisibleIndex = 0;
                treeList1.EndUpdate();
                treeList1.BeginUnboundLoad();
                TreeListNode parentNode = treeList1.AppendNode(new object[] { "Бүгд" }, null);
                parentNode.Tag = "";
                string distCode = "Бүгд";
                foreach (vw_DistAndQuart d in Dist)
                {
                    if (distCode.Equals(d.DistrictCode))
                    {
                        TreeListNode childNode = treeList1.AppendNode(new object[] { d.QuartName }, parentNode);
                        childNode.Tag = d.QuarterCode;
                    }
                    else
                    {
                        parentNode = treeList1.AppendNode(new object[] { d.DistName }, null);
                        parentNode.Tag = d.DistrictCode;
                        TreeListNode childNode = treeList1.AppendNode(new object[] { d.QuartName }, parentNode);
                        childNode.Tag = d.QuarterCode;
                        distCode = d.DistrictCode;
                    }
                }
                treeList1.EndUnboundLoad();
                #endregion
                cmbASection.Properties.DataSource = obj.SectionListForSearch();
                cmbASection.Properties.DisplayMember = "Name";
                cmbASection.Properties.ValueMember = "SectionNo";
                cmbASection.ItemIndex = 0;
                cmbCollector.Properties.Items.Add(new ComboItem() { Display = "", StrValue = "" });
                cmbCollector.Properties.Items.AddRange(obj.CollectorList().Select(s => new ComboItem() { Display = s.Name, StrValue = s.UserId.ToString() }).ToArray());
                cmbCollector.SelectedIndex = cmbCollector.Properties.Items.Count > 0 ? 0 : -1;
                #region fill cmbBank
                cmbBank.Properties.DataSource = obj.BankListForSearch();
                cmbBank.Properties.DisplayMember = "Name";
                cmbBank.Properties.ValueMember = "BankID";
                //cmbBank.Properties.BestFitMode = BestFitMode.BestFit;
                //cmbBank.Properties.SearchMode = SearchMode.AutoComplete;                
                cmbBank.ItemIndex = 0;
                #endregion
            }
        }

        private void cmbBank_EditValueChanged(object sender, EventArgs e)
        {
            using (EnquiryClient obj1 = new EnquiryClient(Globals.Token))
            {
                //cmbKass.Properties.DataSource = null;                
                cmbKass.Properties.DataSource = obj1.BankBranchesForSearch(Convert.ToInt32(cmbBank.EditValue));
                cmbKass.Properties.DisplayMember = "Name";
                cmbKass.Properties.ValueMember = "BranchID";
                cmbKass.ItemIndex = 0;
            }
        }

        private void panelControl1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void frmContractList_Load(object sender, EventArgs e)
        {
            if (File.Exists(this.Name + ".xml"))
            {
                viewApartment.RestoreLayoutFromXml(this.Name + ".xml");
            }
            loadData();
            tlstLoaded = true;
        }

        private void checkEdit1_CheckedChanged(object sender, EventArgs e)
        {
            dt1.Enabled = checkEdit1.Checked;
            dt2.Enabled = checkEdit1.Checked;
        }

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void gridControl1_DoubleClick(object sender, EventArgs e)
        {
            if (viewApartment.SelectedRowsCount < 1)
            {
                Globals.Warr("Өгөгдөл сонгогдоогүй байна!");
                return;
            }

            vw_Contracts cont = (vw_Contracts)viewApartment.GetRow(viewApartment.GetSelectedRows()[0]);
            if (IsBrowse)
            {
                this.Contract = cont;
                DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            else
            {
                frmContract frm = new frmContract();
                frm.Tag = cont.ContractNo;
                if (frm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    loadGrid();
                }
            }
        }

        private void barButtonItem7_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                saveFileDialog1.Title = "Specify Destination Filename";
                saveFileDialog1.Filter = "excell Files|*.xls";
                saveFileDialog1.FilterIndex = 1;
                saveFileDialog1.OverwritePrompt = true;
                saveFileDialog1.CreatePrompt = true;

                if (saveFileDialog1.ShowDialog() == DialogResult.OK & !string.IsNullOrEmpty(saveFileDialog1.FileName))
                {

                    gridApartment.ExportToExcelOld(saveFileDialog1.FileName);
                }
            }
            catch (Exception ex)
            {
                Globals.Err(ex.Message);
            }
        }

        private void treeList1_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            if (tlstLoaded == false) return;
            if (treeList1.Selection[0].ParentNode == null)
            {
                //if (treeList1.Selection[0].Tag.ToString().Length > 0)
                //{
                //   loadGrid();
                //}

            }
            else
            {
                loadGrid();
            }
        }

        private void frmContractList_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F3)
            {
                loadGrid();
            }

        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }

        #region Гүйлгээний товчуудыг нэмэв
        private void btnExtend_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int[] r=viewApartment.GetSelectedRows();
            if (r.Count() > 0)
            {
                var c = (vw_Contracts)viewApartment.GetRow(r[0]);
                if (c.Status != 0) return;
                frmTransExtend frm = new frmTransExtend(c.ContractNo);
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    loadData();
                }
            }
        }

        private void btnProductBuy_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int[] r = viewApartment.GetSelectedRows();
            if (r.Count() > 0)
            {
                var c = (vw_Contracts)viewApartment.GetRow(r[0]);
                if (c.Status != 0) return;
                frmTransSell frm = new frmTransSell(c.ContractNo);
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    loadData();
                }
            }
        }
        #endregion

        private void btnPause_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int[] r = viewApartment.GetSelectedRows();
            if (r.Count() > 0)
            {
                var c = (vw_Contracts)viewApartment.GetRow(r[0]);
                if (c.Status != 0) return;
                frmTransPause frm = new frmTransPause(c.ContractNo);
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    loadData();
                }
            }

        }

        private void btnRun_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            int[] r = viewApartment.GetSelectedRows();
            if (r.Count() > 0)
            {
                var c = (vw_Contracts)viewApartment.GetRow(r[0]);
                if (c.Status != 2) return;
                frmTransRun frm = new frmTransRun(c.ContractNo);
                if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    loadData();
                }
            }

        }

        private void btnTransaction_Click(object sender, EventArgs e)
        {
            HyperLinkEdit link = (HyperLinkEdit)sender;
            frmTransactionList frm = new frmTransactionList(long.Parse(link.Text));
            frm.MdiParent = this.MdiParent;
            frm.Show();
            
        }

        private void barButtonItem8_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (viewApartment.SelectedRowsCount < 1)
            {
                Globals.Warr("Өгөгдөл сонгогдоогүй байна!");
                return;
            }

            vw_Contracts cont = (vw_Contracts)viewApartment.GetRow(viewApartment.GetSelectedRows()[0]);
            if (IsBrowse)
            {
                this.Contract = cont;
                DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            else
            {
                frmContract_new frm = new frmContract_new();
                frm.Tag = cont.ContractNo;
                if (frm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    loadGrid();
                }
            }
        }

        private void frmContractList_FormClosing(object sender, FormClosingEventArgs e)
        {
            viewApartment.SaveLayoutToXml(this.Name + ".xml");
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            txtMail.Text = string.Empty;
            txtPhone.Text = string.Empty;
            txtBill.Text = string.Empty;
            txtUser.Text = string.Empty;
            txtProd1.Text = string.Empty;
        }

        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (viewApartment.SelectedRowsCount < 1)
            {
                Globals.Warr("Өгөгдөл сонгогдоогүй байна!");
                return;
            }

            vw_Contracts cont = (vw_Contracts)viewApartment.GetRow(viewApartment.GetSelectedRows()[0]);
            if (IsBrowse)
            {
                this.Contract = cont;
                DialogResult = System.Windows.Forms.DialogResult.OK;
            }
            else
            {
                frmContract frm = new frmContract();
                frm.isCancel = true;
                frm.Tag = cont.ContractNo;
                if (frm.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    loadGrid();
                }
            }
        }

        

      
    }
}
